﻿<?LassoScript
/*
This is an Open Source calendar based on the Jquery plugin Weekcalendar by Rob Monie with some additional Javascript by Jolle Carlestam. The server side is all Lasso on Knop written by Jolle Carlestam.

The file ajax.lasso is used for all data interaction handling.
It's used for 
* Retrieving events from the table both for display within the calendar and for export to Icalendar files
* Adding, updating and deleting events
* Importing Icalendar files

Status
2009-10-13	JC	Fixed bug where line feeds destroyed the Json object
2009-10-12	JC	Tweaked handling of incoming dates to deal with IE formatting of dates. Should be a way to ensure that all browsers send the same date types

*/


include('cfg__calendar.inc');

// language strings
include('language.inc');

if(true);
// Replace true with an authorisation check if needed

	var(	'actionType' = action_param('actionType'));
	!lasso_tagexists('jina_weekStartStop') ? include('jina_weekStartStop.inc');

	select(true);

		case($actiontype == 'getcalendarevents');

			var('startdate' = action_param('start'));
			$startdate -> size == 0 ? $startdate = date();
			var('range' = jina_weekStartStop(date($startdate)));

			// create a database object for the events
			var('dActivity' = knop_database(
				-database = $database,
				-table = 'clndr_activity',
				-username = $username,
				-password = $userpw,
				-keyfield = 'keyfield'));


			var('searchparams' =  array( -gte, 'CLNDR_startdate' = $range -> first, -lte, 'CLNDR_startdate' = $range -> last, -maxrecords = 'all', -skiprecords = 0));

			// get list of records
			$dActivity -> select(-search = $searchparams);

			var('desc' = NULL);
			// start building a Json object
			'[';


			records(-inlinename = $dActivity -> inlinename);
				$desc = field('CLNDR_description', -encodenone);
				$desc -> replace('\r\n','####');
				$desc -> replace('\r','####');
				$desc -> replace('\n','####');
				$desc -> replace('####','\\n');

				loop_count > 1 ? ',\r';
				'	{"id":"';
				field('keyfield');
				'","start":"';
				field('CLNDR_startdate');
				'T';
				field('CLNDR_starttime');
				'","end":"';
				field('CLNDR_startdate');
				'T';
				field('CLNDR_stoptime');
				'","summary":"';
				field('CLNDR_summary', -encodenone);
				'","description":"'
				$desc;
				'","location":"'
				field('CLNDR_location', -encodenone);
				'"}';
			/records;


			']'; // Json object done

		case($actiontype == 'updateevent');

			var('errormessage' = array);
			// create a database object for the event
			var('dActivity' = knop_database(
				-database = $database,
				-table = 'clndr_activity',
				-username = $username,
				-password = $userpw,
				-keyfield = 'keyfield'));

			var('recfields' = array);
			$recfields -> insert( 'datetime_mod' = (date -> format('%Q %T')));
			$recfields -> insert( 'user_mod' = 'webuser');

			if(action_param('eventAction') != 'dropped' && action_param('eventAction') != 'resized');
				$recfields -> insert( 'CLNDR_summary' = action_param('summary'));
				$recfields -> insert( 'CLNDR_location' = action_param('location'));
				$recfields -> insert( 'CLNDR_description' = action_param('description'));
			/if;

			var('start' = date(action_param('start'), -format = ('%a %b %d %Y %T')));
			$start -> type != 'date' ? $start = date(action_param('start'), -format = ('%a %b %d %T UTC%z %Y'));
			var('stop' = date(action_param('end'), -format = ('%a %b %d %Y %T')));
			$stop -> type != 'date' ? $stop = date(action_param('stop'), -format = ('%a %b %d %T UTC%z %Y'));
			
			$start -> type != 'date' || $stop -> type != 'date' ? $errormessage -> insert($lang_errormessages -> code8501);
//$errormessage -> insert('testmessage');
			if($errormessage -> size == 0);
				$recfields -> insert( 'CLNDR_startdate' = $start -> format('%Q'));
				$recfields -> insert( 'CLNDR_starttime' = $start -> format('%T'));
				$recfields -> insert( 'CLNDR_stopdate' = $stop -> format('%Q'));
				$recfields -> insert( 'CLNDR_stoptime' = $stop -> format('%T'));

				$dActivity -> saverecord( -fields = $recfields, 
					-keyvalue = action_param('id'));

				if($dActivity -> error_code);
					$lang_messages -> servererroroccurred;
					' \r';
					$dActivity -> error_msg;
					var('header' = Content_Header);
					$header -> replace('200 OK', '400 Bad Request');
					Content_Header($header);
				/if;
			else;
				$errormessage -> join('<br>');
				var('header' = Content_Header);
				$header -> replace('200 OK', '400 Bad Request');
				Content_Header($header);
			/if;

		case($actiontype == 'newevent');

			var('errormessage' = array);
			// create a database object for the event
			var('dActivity' = knop_database(
				-database = $database,
				-table = 'clndr_activity',
				-username = $username,
				-password = $userpw,
				-keyfield = 'keyfield'));

			var('recfields' = array);
			$recfields -> insert( 'datetime_create' = (date -> format('%Q %T')));
			$recfields -> insert( 'datetime_mod' = (date -> format('%Q %T')));
			$recfields -> insert( 'user_mod' = 'webuser');
			$recfields -> insert( 'user_create' = 'webuser');

			$recfields -> insert( 'CLNDR_location' = action_param('location'));
			$recfields -> insert( 'CLNDR_summary' = action_param('summary'));
			$recfields -> insert( 'CLNDR_description' = action_param('description'));

			var('start' = date(action_param('start'), -format = ('%a %b %d %Y %T')));
			$start -> type != 'date' ? $start = date(action_param('start'), -format = ('%a %b %d %T UTC%z %Y'));
			var('stop' = date(action_param('end'), -format = ('%a %b %d %Y %T')));
			$stop -> type != 'date' ? $stop = date(action_param('stop'), -format = ('%a %b %d %T UTC%z %Y'));
			
			$start -> type != 'date' || $stop -> type != 'date' ? $errormessage -> insert($lang_errormessages -> code8501);

			if($errormessage -> size == 0);
				$recfields -> insert( 'CLNDR_startdate' = $start -> format('%Q'));
				$recfields -> insert( 'CLNDR_starttime' = $start -> format('%T'));
				$recfields -> insert( 'CLNDR_stopdate' = $stop -> format('%Q'));
				$recfields -> insert( 'CLNDR_stoptime' = $stop -> format('%T'));

				$dActivity -> addrecord( -fields = $recfields, 
					-keyvalue = action_param('id'));

				if($dActivity -> error_code);
					$lang_messages -> servererroroccurred;
					' \r';
					$dActivity -> error_msg;
					$dActivity -> error_msg;
					var('header' = Content_Header);
					$header -> replace('200 OK', '400 Bad Request');
					Content_Header($header);
				/if;
			else;
				$errormessage -> join('<br>');
				var('header' = Content_Header);
				$header -> replace('200 OK', '400 Bad Request');
				Content_Header($header);
			/if;

		case($actiontype == 'deleteevent');

			// create a database object for the event
			var('dActivity' = knop_database(
				-database = $database,
				-table = 'clndr_activity',
				-username = $username,
				-password = $userpw,
				-keyfield = 'keyfield'));

			$dActivity -> deleterecord(
				-keyvalue = action_param('id'));

			if($dActivity -> error_code);
				$lang_messages -> servererroroccurred;
				' \r';
				$dActivity -> error_msg;
			/if;
		case($actiontype == 'getNewID');

			knop_unique;

		case($actiontype == 'exporticalweek');

			var('start' = (action_param('start') -> size == 0) ?
				jina_weekStartStop(date) -> first |
				action_param('start'));
			var('end' = (action_param('end') -> size == 0) ?
				jina_weekStartStop(date) -> last |
				action_param('end'));

			// create a database object for the events
			var('dActivity' = knop_database(
				-database = $database,
				-table = 'clndr_activity',
				-username = $username,
				-password = $userpw,
				-keyfield = 'keyfield'));


			var('searchparams' =  array( -gte, 'CLNDR_startdate' = $start, -lte, 'CLNDR_startdate' = $end, -maxrecords = 'all', -skiprecords = 0));

			// get list of records
			$dActivity -> select(-search = $searchparams);

			var('cal' = ical_calendar);
			var('event' = null);
			var('start' = null);
			var('end' = null);

			records(-inlinename = $dActivity -> inlinename);

				$start = date(field('CLNDR_startdate') + ' ' + field('CLNDR_starttime'));
				$end = date(field('CLNDR_stopdate') + ' ' + field('CLNDR_stoptime'));
				$event = ical_event;
				$event -> addattribute('UID', field('keyfield'));
				$event -> addattribute('DTStart', $start);
				$event -> addattribute('DTEnd', $end);
				$event -> addattribute('SUMMARY', field('CLNDR_summary'));
				$event -> addattribute('LOCATION', field('CLNDR_location'));
				$event -> addattribute('DESCRIPTION', field('CLNDR_description'));
				$cal -> insert($event);

			/records;

			if(client_browser >> 'Mac');

				file_serve( $cal, -file = 'Icalendar-' + (date -> format('%Q_%H%M')) + '.ics', -type = 'application/octet-stream', -charset = "UTF-8");

			else;

				var('winCal' = (bytes));
				$winCal -> importstring( $cal, 'UTF-16');

				file_serve( $winCal, -file = 'Icalendar-' + (date -> format('%Q_%H%M')) + '.ics', -type = 'application/octet-stream');
			/if;

		case($actiontype == 'exporticalall');

			// create a database object for the events
			var('dActivity' = knop_database(
				-database = $database,
				-table = 'clndr_activity',
				-username = $username,
				-password = $userpw,
				-keyfield = 'keyfield'));


			var('searchparams' =  array(-maxrecords = 'all', -skiprecords = 0));

			// get list of records
			$dActivity -> select(-sql = 'SELECT * FROM clndr_activity', -search = $searchparams);

			var('cal' = ical_calendar);
			var('event' = null);
			var('start' = null);
			var('end' = null);

			records(-inlinename = $dActivity -> inlinename);
				$start = date(field('CLNDR_startdate') + ' ' + field('CLNDR_starttime'));
				$end = date(field('CLNDR_stopdate') + ' ' + field('CLNDR_stoptime'));
				$event = ical_event;
				$event -> addattribute('UID', field('keyfield'));
				$event -> addattribute('DTStart', $start);
				$event -> addattribute('DTEnd', $end);
				$event -> addattribute('SUMMARY', field('CLNDR_summary'));
				$event -> addattribute('LOCATION', field('CLNDR_location'));
				$event -> addattribute('DESCRIPTION', field('CLNDR_description'));
				$cal -> insert($event);
			/records;

			if(client_browser >> 'Mac');
				file_serve( $cal, -file = 'Icalendar-' + (date -> format('%Q_%H%M')) + '.ics', -type = 'application/octet-stream', -charset = "UTF-8");
			else;

				var('winCal' = (bytes));
				$winCal -> importstring( $cal, 'UTF-16');

				file_serve( $winCal, -file = 'Icalendar-' + (date -> format('%Q_%H%M')) + '.xls', -type = 'application/octet-stream');
			/if;

		case($actiontype == 'initimport');
			'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html lang="sv">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<title>' + $lang_labels -> importLbl + '</title>
        <link rel="stylesheet" type="text/css" href="reset.css">
        <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/start/jquery-ui.css">
        <link rel="stylesheet" type="text/css" href="jquery.weekcalendar.css">
        <link rel="stylesheet" type="text/css" href="weekcalendar.css">

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
        <script type="text/javascript" src="jquery.weekcalendar.js"></script>

	<script type="text/javascript" language="javascript">
$(document).ready(function() {

	$("#icalfile").change(function() {
		$("#importicalform").submit();
	});

});

</script>
</head>
<body>
        <div id="importical">
        	<form action="ajax.lasso" method="post" id="importicalform" name="importicalform" enctype="multipart/form-data">
        		<input name="actionType" type="hidden" value="execimport">
        		<input name="icalfile" id="icalfile" type="file">
        	</form>
        </div>

</body>
</html>
';
		case($actiontype == 'execimport');
			var('message' = array);
			var('icalimport' = string);

			inline(-username = $username,
				-password = $userpw);

				if(file_uploads -> size > 0);
					var('icalfilecontent' = file_read(file_uploads -> first ->find('path')));

					protect;
						$icalimport = ical_parse($icalfilecontent);
					/protect;
					if($icalimport -> type == 'Calendar');

						// create a database object for the events
						var('dActivity' = knop_database(
							-database = $database,
							-table = 'clndr_activity',
							-username = $username,
							-password = $userpw,
							-keyfield = 'keyfield'));

						var('sql' = 'INSERT INTO clndr_activity (keyfield, datetime_create, datetime_mod, user_create, user_mod, CLNDR_summary, CLNDR_location, CLNDR_description, CLNDR_startdate, CLNDR_stopdate, CLNDR_starttime, CLNDR_stoptime) VALUES ');
						var('start' = null);
						var('end' = null);
						var('uid' = null);
						var('summary' = null);
						var('location' = null);
						var('description' = null);

						iterate($icalimport -> events, var('icalevents'));

							$uid = $icalevents -> getattribute('UID');
							$summary = $icalevents -> getattribute('Summary');
							$location = $icalevents -> getattribute('Location');
							$description = $icalevents -> getattribute('Description');
							$start = $icalevents -> getattribute('DTStart');
							$end = $icalevents -> getattribute('DTEnd');

							$uid -> type == 'Attribute' ? $uid = $uid -> value | $uid = knop_unique;
							$summary -> type == 'Attribute' ? $summary = $summary -> value;
							$location -> type == 'Attribute' ? $location = $location -> value;
							$description -> type == 'Attribute' ? $description = $description -> value;
							$start -> type == 'Attribute' ? $start = $start -> value;
							$end -> type == 'Attribute' ? $end = $end -> value;

							$sql += ' ("' +
							$uid + '", NOW(), NOW(), "' + $calusername + '", "' + $calusername + '", "' +
							encode_sql($summary) + '", "' +
							encode_sql($location) + '", "' +
							encode_sql($description) + '", "' +
							$start -> format('%Q') + '", "' +
							$end -> format('%Q') + '", "' +
							$start -> format('%T') + '", "' +
							$end -> format('%T') + '"' +
							'),';

						/iterate;
						$sql -> removetrailing(',');
						$sql += ' ON DUPLICATE KEY UPDATE datetime_mod = NOW(), CLNDR_summary=VALUES(CLNDR_summary), CLNDR_location = VALUES(CLNDR_location), CLNDR_description = VALUES(CLNDR_description), CLNDR_startdate = VALUES(CLNDR_startdate), CLNDR_stopdate = VALUES(CLNDR_stopdate), CLNDR_starttime = VALUES(CLNDR_starttime), CLNDR_stoptime = VALUES(CLNDR_stoptime)';

						$dActivity -> select(-sql = $sql);
						$dActivity -> error_code ? $message -> insert($dActivity -> error_msg);

					else;
						$message -> insert($lang_errormessages -> code8511);
					/if;

				else;
					$message -> insert($lang_errormessages -> code8510);
				/if;

			/inline;

			if($message -> size > 0);
				$message -> join('<br>');
			else;
			'<script type="text/javascript" language="javascript">
				window.opener.wc_refresh();
				window.close();
</script>';
			/if;
		case;
			'Not supposed to happen!<br>\r';
			lp_client_params;


	/select;

/if;

?>